<template>
  <div>
    <!-- 上传区域 -->
    <el-dialog
      v-model="open"
      :close-on-click-modal="false"
      :title="title"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx,.xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        :on-error="handleFileError"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖入此处,或
          <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip" style="color: red;">提示:仅允许导入"xls"或"xlsx"格式文件!<el-link type="info" style="font-size: 12px;" @click="importTemplate">下载模板</el-link></div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确定</el-button>
          <el-button @click="open = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, getCurrentInstance, defineProps, reactive } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { getToken, getTokenType } from '@/utils/auth'

const tokenType = getTokenType(),
  getList = ref({
    type: Function,
    default: () => {},
  })
const open = ref(false),
  title = ref(null),
  upload = reactive({
    isUploading: false,
    updateSupport: 0,
    headers: { Authorization: `${ tokenType }${ getToken() }` },
    url: `${ import.meta.env.VITE_BASE_API }/system/customer/pool/import`,
  }),
  {
    appContext: {
      config: {
        globalProperties: { $download },
      },
    },
  } = getCurrentInstance()

const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}
const { proxy } = getCurrentInstance() as any
const handleFileSuccess = (res) => {
  open.value = false
  upload.isUploading = false
  proxy.$refs.upload.clearFiles()
  ElMessageBox.alert(res.msg, '导入结果', { dangerouslyUseHTMLString: true })
  getList
}
// 模板导出
const importTemplate = () => {
  $download('system/pool/exportCustPool/template', {}, `下载模板_${ new Date().getTime() }.xlsx`)
}
const submitFileForm = () => {
  proxy.$refs.upload.submit()
}
const handleFileError = () => {
  proxy.upload.isUploading = false
  proxy.$refs.upload.clearFiles()
  proxy.$alert('异常导入')
}
defineExpose({
  open,
  title,
})
</script>
